import pool from '@/server/db'
import joi from 'joi'
import md5 from 'md5'
import { RowDataPacket, ResultSetHeader } from 'mysql2'
import r from '@/server/utils/r'

const schema = joi.object({
  nickname: joi.string().required(),
  password: joi.string().required(),
  phone: joi.string().pattern(/1\d{10}/),
})

export default defineEventHandler(async event => {
  const body = await readBody(event)
  // 数据验证
  try {
    const value = await schema.validateAsync(body)
  } catch (err) {
    return r('数据验证错误：' + err)
  }
  // 验证手机号是否注册
  try {
    const [result] = await pool.execute(
      'SELECT * FROM `users` where `phone`=?',
      [body.phone]
    )

    if ((result as RowDataPacket[]).length > 0) return r('该号码已经注册')
  } catch (err) {
    return r('手机号验证出错：' + err)
  }
  // 加密密码，注册账号
  try {
    const salt = 'sqfqsffr0'
    const password = md5(md5(body.password) + salt)
    const [result] = await pool.execute(
      'insert into `users` (`nickname`, `phone`, `password`) value (?,?,?)',
      [body.nickname, body.phone, password]
    )
    if ((result as ResultSetHeader).affectedRows === 1) {
      return r('注册成功', 1)
    }
    return { result }
  } catch (error) {
    return r('注册失败：' + error)
  }
})
